package com.ruoyi.web.controller.module.survey;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.module.survey.SurveyQuestion;
import com.ruoyi.system.domain.module.survey.SurveyUserRecordInfo;
import com.ruoyi.system.service.module.survey.ISurveyQuestionService;
import com.ruoyi.system.service.module.survey.ISurveyService;
import com.ruoyi.system.service.module.survey.ISurveyUserRecordInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 问卷调查的用户填报数据Controller
 *
 * @author ruoyi
 * @date 2021-09-05
 */
@Validated
@Api(value = "问卷调查的用户填报数据控制器", tags = {"问卷调查的用户填报数据管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/survey/record/info")
public class SurveyUserRecordInfoController extends BaseController {

    private final ISurveyService surveyService;
    private final ISurveyQuestionService surveyQuestionService;
    private final ISurveyUserRecordInfoService surveyUserRecordInfoService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;
    /**
     * 查询问卷调查的用户填报数据列表
     */
    @ApiOperation("查询问卷调查的用户填报数据列表")
    @PreAuthorize("@ss.hasPermi('module:survey_record:list')")
    @GetMapping("/list")
    public TableDataInfo<SurveyUserRecordInfo> list(@Validated SurveyUserRecordInfo surveyUserRecordInfo) {
        QueryWrapper<SurveyUserRecordInfo> qw = new QueryWrapper<>();
        if(surveyUserRecordInfo.getRecordId()!=null){
            qw.eq("record_id",surveyUserRecordInfo.getRecordId());
        }
        TableDataInfo<SurveyUserRecordInfo> td = PageUtils.buildDataInfo(surveyUserRecordInfoService.page(PageUtils.buildPage(),qw));
        List<SurveyUserRecordInfo> list = td.getRows();

        list.forEach(record->{
            SurveyQuestion question = surveyQuestionService.getById(record.getQuestionId());
            if(question!=null){
				boolean p = true;
				//判断是否为数值
				if (question.getQuestionType()==0){
					for (int i = 0; i < record.getAnswer().length(); i++) {
						if (!Character.isDigit(record.getAnswer().charAt(i))) {
							p = false;
						}
					}
					record.setQuestion(question.getQuestion());
					if (p){
						JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
						JSONObject jsonObject = (JSONObject)jsonArray.get(Integer.parseInt(record.getAnswer()));
						if(jsonObject!=null && jsonObject.containsKey("value")){
							record.setAnswerValue(jsonObject.getStr("value"));
						}
					}
				}
				if (question.getQuestionType()==1){
					record.setQuestion(question.getQuestion());
					record.setAnswerValue(record.getAnswer());
				}
				if (question.getQuestionType()==2){
					record.setQuestion(question.getQuestion());
					record.setImgValue(imgUrl+record.getAnswer());
				}
            }
        });
        return td;
    }

	@ApiOperation("查询问卷调查的用户填报数据列表")
	@PreAuthorize("@ss.hasPermi('module:survey_record:list')")
	@GetMapping("/lists")
	public List<SurveyUserRecordInfo> lists(@Validated SurveyUserRecordInfo surveyUserRecordInfo) {
		QueryWrapper<SurveyUserRecordInfo> qw = new QueryWrapper<>();
		if(surveyUserRecordInfo.getRecordId()!=null){
			qw.eq("record_id",surveyUserRecordInfo.getRecordId());
		}
		List<SurveyUserRecordInfo> list = surveyUserRecordInfoService.list(qw);

		for (SurveyUserRecordInfo record:list){
			SurveyQuestion question = surveyQuestionService.getById(record.getQuestionId());
			if(question!=null){
				boolean p = true;
				//判断题目类型
				if (question.getQuestionType()==0){
					for (int i = 0; i < record.getAnswer().length(); i++) {
						if (!Character.isDigit(record.getAnswer().charAt(i))) {
							p = false;
						}
					}
					record.setQuestion(question.getQuestion());
					if (p){
						JSONArray jsonArray = JSONUtil.parseArray(question.getAnswerSection());
						JSONObject jsonObject = (JSONObject)jsonArray.get(Integer.parseInt(record.getAnswer()));
						if(jsonObject!=null && jsonObject.containsKey("value")){
							record.setAnswerValue(jsonObject.getStr("value"));
						}
					}
				}
				if (question.getQuestionType()==1){
					record.setQuestion(question.getQuestion());
					record.setAnswerValue(record.getAnswer());
				}
				if (question.getQuestionType()==2){
					record.setQuestion(question.getQuestion());
					record.setImgValue(imgUrl+record.getAnswer());
				}
			}
		};
		return list;
	}

    /**
     * 导出问卷调查的用户填报数据列表
     */
    @ApiOperation("导出问卷调查的用户填报数据列表")
    @PreAuthorize("@ss.hasPermi('module:survey_record:export')")
    @Log(title = "问卷调查的用户填报数据", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<SurveyUserRecordInfo> export(@Validated SurveyUserRecordInfo recordInfo) {
        List<SurveyUserRecordInfo> list = surveyUserRecordInfoService.list();
        ExcelUtil<SurveyUserRecordInfo> util = new ExcelUtil<SurveyUserRecordInfo>(SurveyUserRecordInfo.class);
        return util.exportExcel(list, "问卷调查的用户填报数据");
    }

    /**
     * 获取问卷调查的用户填报数据详细信息
     */
    @ApiOperation("获取问卷调查的用户填报数据详细信息")
    @PreAuthorize("@ss.hasPermi('module:survey_record:query')")
    @GetMapping("/{id}")
    public AjaxResult<SurveyUserRecordInfo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
		SurveyUserRecordInfo surveyUserRecord = surveyUserRecordInfoService.getById(id);
        return AjaxResult.success(surveyUserRecord);
    }

    /**
     * 新增问卷调查的用户填报数据
     */
    @ApiOperation("新增问卷调查的用户填报数据")
    @PreAuthorize("@ss.hasPermi('module:survey_record:add')")
    @Log(title = "问卷调查的用户填报数据", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody SurveyUserRecordInfo recordInfo) {
        return toAjax(surveyUserRecordInfoService.save(recordInfo) ? 1 : 0);
    }

    /**
     * 修改问卷调查的用户填报数据
     */
    @ApiOperation("修改问卷调查的用户填报数据")
    @PreAuthorize("@ss.hasPermi('module:survey_record:edit')")
    @Log(title = "问卷调查的用户填报数据", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody SurveyUserRecordInfo recordInfo) {
        return toAjax(surveyUserRecordInfoService.updateById(recordInfo) ? 1 : 0);
    }

    /**
     * 删除问卷调查的用户填报数据
     */
    @ApiOperation("删除问卷调查的用户填报数据")
    @PreAuthorize("@ss.hasPermi('module:survey_record:remove')")
    @Log(title = "问卷调查的用户填报数据" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(surveyUserRecordInfoService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
